import type { Ref } from 'vue';
import { NPopover, NCheckboxGroup, NCheckbox } from 'naive-ui';
import style from './index.module.scss';
import { LcSvgIcon } from '@/components/LcSvgIcon';
import editIcon from '@/assets/img/common/edit.png';
import { cloneDeep } from 'lodash';
import type { DataTableColumn, DataTableColumns, DataTableBaseColumn } from 'naive-ui';

interface ParamsType<T = any> {
	/** 原始数据 */
	sourceColumns: T[] | Ref<T[]>;
	/** 默认绑定的数组 */
	defaultBindArr?: any[] | Ref<any[]>;
	/** localstorage的key */
	localKey: string | Ref<string>;
	/** 是否是表格 */
	isTable?: boolean;
	/** 是否固定(表格时生效) */
	fixed?: boolean;
	/** popover隐藏事件 */
	onPopHiden?: (columnsArr: any[], bindArr: Ref<any[]>) => void;
	/** 创建成功回调 */
	onCreated?: (columnsArr: any[], bindArr: Ref<any[]>) => void;
	/** sourceColumns的绑定值和显示值 */
	columnProps?: {
		value: string;
		label: string;
	};
}

/** 设置table的列
 * @param sourceColumns 原始数据
 * @param localKey localstorage的key
 * @param isTable 是否是表格,默认值为true
 * @param fixed 是否固定，默认值为false (isTable为true时生效)
 * @param onPopHiden popover隐藏事件
 * @param onCreated 创建成功
 */
export function useSuffixSetting<T>({
	sourceColumns,
	localKey,
	onPopHiden,
	onCreated,
	fixed,
	defaultBindArr,
	isTable = true,
	// columnProps = { label: 'key', value: 'title' },
	columnProps = { label: 'title', value: 'key' },
}: ParamsType<T>) {
	const bindArr = ref<any[]>([]);
	const componetBindArr = ref<any[]>([]);
	const componetSourceColumns = computed(() => {
		if (!localStorage[unref(localKey)]) {
			initDefaultBindArr();
		}
		// return JSON.parse(JSON.stringify(unref(sourceColumns)));
		return cloneDeep(unref(sourceColumns));
	});

	function initDefaultBindArr() {
		if (defaultBindArr) {
			bindArr.value = [...unref(defaultBindArr)];
			componetBindArr.value = [...unref(defaultBindArr)];
		} else {
			bindArr.value = unref(sourceColumns).map(item => item[columnProps.value]);
			componetBindArr.value = unref(sourceColumns).map(item => item[columnProps.value]);
		}
	}

	/** 初始化获取local storage中的值 */
	onMounted(() => {
		init();
	});

	function init() {
		if (localStorage[unref(localKey)]) {
			bindArr.value = JSON.parse(localStorage[unref(localKey)]);
			componetBindArr.value = JSON.parse(localStorage[unref(localKey)]);
		} else {
			initDefaultBindArr();
		}
	}

	watch(
		() => localKey,
		value => {
			init();
		},
		{ deep: true }
	);

	nextTick(() => {
		setTimeout(() => {
			onCreated && onCreated(getFilterColumns(), bindArr);
		}, 100);
	});

	/** 获取过滤后的columns */
	function getFilterColumns(): T[] {
		const arr = unref(componetSourceColumns).filter(item => {
			return unref(bindArr).includes(item[columnProps.value]);
		});

		// const newArr = JSON.parse(JSON.stringify(arr));
		const newArr = cloneDeep(arr);
		// 表格处理
		if (isTable && newArr.length > 0) {
			if (fixed) {
				(newArr as DataTableColumns).push({
					key: 'columnSetting',
					title() {
						return <SuffixSetting />;
					},
					width: 50,
					align: 'center',
					fixed: 'right',
					render() {
						return '';
					},
				} as DataTableColumn);
			} else {
				const last = newArr.length - 1;
				(newArr[last] as DataTableBaseColumn).filter = 'default';
				(newArr[last] as DataTableBaseColumn).filterOptionValue = null;
				(newArr[last] as DataTableBaseColumn).renderFilterIcon = () => {
					return <SuffixSetting />;
				};
				(newArr[last] as DataTableBaseColumn).renderFilterMenu = () => '';
			}
		}

		return newArr;
	}

	/** popover隐藏 */
	function popOverHidden(value) {
		if (!value) {
			bindArr.value = [...unref(componetBindArr)];
			localStorage.setItem(unref(localKey), JSON.stringify(unref(bindArr)));
			onPopHiden && onPopHiden(getFilterColumns(), bindArr);
		}
	}

	/** 组件 */
	const SuffixSetting = defineComponent({
		name: 'RightTool',
		emits: ['queryTable', 'update:showSearch', 'changeSize'],
		setup(props, { emit }) {
			return () => (
				<>
					<NPopover placement="left" trigger="click" onUpdateShow={popOverHidden}>
						{{
							default: () => {
								return (
									<div class={style['popContent']}>
										<NCheckboxGroup
											value={componetBindArr.value}
											onUpdateValue={value => {
												componetBindArr.value = value;
											}}
										>
											<div class={style['spaceContet']}>
												{unref(componetSourceColumns).map(item => {
													return (
														<NCheckbox
															value={item[columnProps.value]}
															label={item[columnProps.label]}
														/>
													);
												})}
											</div>
										</NCheckboxGroup>
									</div>
								);
							},
							trigger: () => {
								return (
									<div
										class={style['suffixIcon']}
										onClick={e => {
											e.stopPropagation();
										}}
									>
										{/* <LcSvgIcon iconClass='set' size={19}/> */}
										<img src={editIcon} />
									</div>
								);
							},
						}}
					</NPopover>
				</>
			);
		},
	});

	return {
		/** 获取过滤后的columns */
		getFilterColumns,
		/** 组件 */
		SuffixSetting,
	};
}
